const cheerio = require('cheerio')
const htmlDownloader = require('html-downloader')
const digitMap = {
    numberdor:      '.',
    numberzero:     '0',
    numberone:      '1',
    numbertwo:      '2',
    numberthree:    '3',
    numberfour:     '4',
    numberfive:     '5',
    numbersix:      '6',
    numberseven:    '7',
    numbereight:    '8',
    numbernine:     '9'
}

;(async function() {
    let i = 1, page = 1
    function tra($, elms) {
        let ret = ''
        elms.each(function(idx, elm) {
            ret += digitMap[$(elm).attr('class')]
        })
        return ret
    }
    do {
        // let url = `http://www.tmsf.com/newhouse/property_330184_459814257_price.htm?isopen=1&presellid=&buildingid=&area=&allprice=&housestate=1&housetype=1&page=${i}`
        let url =  `http://www.tmsf.com/newhouse/property_330184_488622146_price.htm?isopen=1&presellid=&buildingid=&area=&allprice=&housestate=1&housetype=1&page=${i}`
        let list = await htmlDownloader(url).catch(console.error)
        let $ = cheerio.load(list)
        if (i === 1) {
            page = Number(($('.spagenext > span').text().match(/\/(\d+)/) || [0])[1]) // 总页数
        }
        $('.ft14 .ft14 .sjtd tr').each(function(idx, elm) {
            let td = $(elm).find('td')
            let td0 = $(td[0]).text().trim()
            let td1 = $(td[1]).text().trim()
            let td2 = tra($, $(td[2]).find('span'))
            let td3 = tra($, $(td[3]).find('span'))
            let td4 = tra($, $(td[4]).find('span'))
            let td5 = tra($, $(td[5]).find('span'))
            let td6 = tra($, $(td[6]).find('span'))
            let td7 = tra($, $(td[7]).find('span'))
            console.log(td0, td1, td2, td3, td4, td5, td6, td7)
        })
    } while (++i <= page)
    // process.exit(0)
})()
